#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @time     : 2019-06-24 10:06
# @Author   : BYF
# file      : mail.py
# @version  :


import os
import smtplib
import traceback
from lefull.conf.config import Config
from email.mime.text import MIMEText  # 邮件正文
from email.mime.image import MIMEImage  # 邮件图片
from email.mime.multipart import MIMEMultipart  # 发送多个部分
from email.mime.application import MIMEApplication  # 发送附件


class Email(object):
    """
    电子邮件
    """

    def __init__(self):
        """
        初始化
        """
        self.config = Config()
        self.smtp_server = self.config.smtp_server  # SMTP服务器
        self.smtp_port = self.config.smtp_port  # 端口
        self.smtp_sender = self.config.smtp_sender  # 发送者
        self.smtp_receivers = self.config.smtp_receivers  # 接收者，多个以逗号分隔
        self.smtp_cc = self.config.smtp_cc  # 抄送者，多个以逗号分隔
        self.smtp_user = self.config.smtp_user  # 用户名
        self.smtp_password = self.config.smtp_password  # 密码

    def send_mail(self, subject, content, is_html=True, files=None, imgs=None):
        """
        发送文本邮件
        :param title: 邮件标题
        :param content: 邮件内容
        :return:
        """
        msg = MIMEMultipart()
        msg["Subject"] = subject  # 定义邮件标题
        msg["From"] = self.smtp_sender  # 定义邮件发送者
        msg["To"] = self.smtp_receivers  # 定义邮件接收者
        msg["Cc"] = self.smtp_cc  # 定义邮件抄送者

        # 添加正文
        if is_html:
            # 添加附件
            if files is None:
                files = []
            for file in files:
                if os.path.isfile(file):
                    file_name = os.path.basename(file)  # 获取附件名称

                part_attach = MIMEApplication(open(file, "rb").read())
                part_attach.add_header("Content-Disposition", "attachment", filename=file_name)
                msg.attach(part_attach)

            msg_mail = ""
            # 添加图片
            if imgs is None:
                imgs = []
            for img in imgs:
                if os.path.isfile(img):
                    img_name = os.path.basename(img)
                    msg_mail += '<p><img src="cid:{img_name}"></p>'.format(img_name=img_name)

                with open(img, "rb") as file:
                    img_data = file.read()

                msg_img = MIMEImage(img_data)
                msg_img.add_header("Content-ID", img_name)
                msg.attach(msg_img)

                # 将图片添加附件
                part_img = MIMEApplication(open(img, "rb").read())
                part_img.add_header("Content-Disposition", "attachment", filename=img_name)
                msg.attach(part_img)
            msg.attach(MIMEText(content + msg_mail, "html", "utf-8"))

        else:
            part_text = MIMEText(content, "plain", "utf-8")
            msg.attach(part_text)

        try:
            mail_server = smtplib.SMTP()
            mail_server.connect(host=self.smtp_server,port=self.smtp_port)
            mail_server.login(self.smtp_user, self.smtp_password)  # 登录
            mail_server.sendmail(  # 发送邮件
                from_addr = msg["From"],
                to_addrs = msg["To"].split(',') + msg["Cc"].split(","),
                msg=msg.as_string(),
            )
            mail_server.quit()  # 退出邮箱
        except:
            print(traceback.format_exc())


def send_mail(subject, content, is_html=True, files=[], imgs=[]):
    mail = Email()
    mail.send_mail(subject, content, is_html=is_html, files=files, imgs=imgs)
    # print("邮件发送成功~！")


if __name__ == '__main__':
    title = "这个是标题邮件和图片"
    content = "这个是内容，其实里面是什么都不重要~！重要的是里面有多个附件和多个图片~！看能不能发送成功咯~！"
    files = ["/Users/Moon/GIT-Data/Virtualenvs/LefullTestEnv/lefull/report/report.zip"]
    imgs = ["/Users/Moon/Desktop/4e733c168e.jpg"]

    # print(imgs)
    send_mail(title, content, files=files, imgs=imgs)
